import typing

from PyQt5.QtCore import Qt
from PyQt5.QtGui import QTextCharFormat, QTextCursor, QBrush, QColor, QGradient, QHideEvent
from PyQt5.QtWidgets import QVBoxLayout, QProgressBar, QTextEdit, QPushButton

from components.widget.mask_dialog_base import MaskDialogBase


class LoadingDialog(MaskDialogBase):
    def __init__(self, parent=None):
        super(LoadingDialog, self).__init__(parent=parent)
        self.vBox = QVBoxLayout(self.widget)

        self.colorProgress = QProgressBar()
        self.colorProgress.setFormat('进度：%p%')
        self.colorProgress.setValue(50)
        self.textEdit = QTextEdit()

        self.textCharFormat = QTextCharFormat()
        self.textCharFormat.setForeground(Qt.white)
        self.textCharFormat.setFontFamily("微软雅黑")
        self.textCharFormat.setFontPointSize(12)

        self.hideButton = QPushButton()
        self.hideButton.setText('关闭')
        self.hideButton.clicked.connect(self.hide)

        self.vBox.addWidget(self.colorProgress)
        self.vBox.addWidget(self.textEdit)
        self.vBox.addWidget(self.hideButton)
        self.cursor = self.textEdit.textCursor()
        self.cursor.movePosition(QTextCursor.End)
        self.textEdit.setTextCursor(self.cursor)

        self._setQss()

    def _setQss(self):
        self.setStyleSheet(
            '''
* {
    font: 12pt "Segoe UI", "Microsoft YaHei";
    color: #fff;
}
QTextEdit {
    background-color: rgba(0, 0, 0, 0.6);
    border: 1px solid rgba(255, 255, 255, 0.08);
    border-radius: 5px;
    padding: 2px 3px 2px 8px;
}

QProgressBar {
    height: 22px;
    text-align: center;
    border: 1px solid rgba(255, 255, 255, 0.08);
    border-radius: 5px;
    background-color: transparent;
}

QProgressBar::chunk {
    border-radius: 11px;
    background: qlineargradient(spread:pad,
    x1: 0,
    y1: 0,
    x2: 1,
    y2: 0,
    stop: 0 #99ffff,
    stop: 1 #9900ff);
}
QPushButton {
    border-radius: 5px;
    border: 1px solid rgba(255, 255, 255, 0.06);
    background-color: rgba(0, 0, 0, 0.5);
}

QPushButton:hover {
    background-color: rgba(166, 164, 164, 0.5);
}

QPushButton:disabled {
    color: rgba(134, 131, 131, 0.85);
}
    '''
        )

    def setText(self, text, brush: typing.Union[QBrush, typing.Union[QColor, Qt.GlobalColor], QGradient] = Qt.red):
        self.textCharFormat.setForeground(brush)
        self.cursor.insertText(text + '\n', self.textCharFormat)
        self.textEdit.setTextCursor(self.cursor)

    def setHtml(self, html):
        self.cursor.insertHtml(html + '<br>')
        self.textEdit.setTextCursor(self.cursor)

    def setValue(self, value):
        self.colorProgress.setValue(value)
        self.update()

    def showEvent(self, e):
        self.setEnabled(False)

    def hideEvent(self, a0: typing.Optional[QHideEvent]) -> None:
        self.textEdit.clear()
        super(LoadingDialog, self).hideEvent(a0)

    def setEnabled(self, a0):
        self.hideButton.setEnabled(a0)
